namespace CSharpPro._1106;

   

public class UserServiceImpl : IUserService
{
    // 使用泛型集合保存用户信息
    private List<User> _users = new List<User>();
    
    // 当前登录用户
    private User _currentUser = null;

    public bool Register(User user, string confirmPassword)
    {
        try
        {
            // 数据验证
            if (user == null)
                throw new ArgumentNullException(nameof(user), "用户信息不能为空");
            
            if (user.Password != confirmPassword)
                throw new ArgumentException("密码和确认密码不一致");
            
            // 检查用户名是否已存在 - 使用foreach循环
            bool usernameExists = false;
            foreach (var existingUser in _users)
            {
                if (existingUser.Username == user.Username)
                {
                    usernameExists = true;
                    break;
                }
            }
            
            if (usernameExists)
                throw new ArgumentException("用户名已存在");
            
            // 添加到集合
            _users.Add(user);
            Console.WriteLine($"用户 {user.Username} 注册成功！");
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"注册失败: {ex.Message}");
            return false;
        }
    }

    public bool Login(string username, string password)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(username))
                throw new ArgumentException("用户名不能为空");
            
            if (string.IsNullOrWhiteSpace(password))
                throw new ArgumentException("密码不能为空");
            
            // 使用foreach循环查找用户
            User foundUser = null;
            foreach (var user in _users)
            {
                if (user.Username == username)
                {
                    foundUser = user;
                    break;
                }
            }
            
            if (foundUser == null)
                throw new ArgumentException("用户名不存在");
            
            if (foundUser.Password != password)
                throw new ArgumentException("密码错误");
            
            _currentUser = foundUser;
            Console.WriteLine($"登录成功！欢迎 {username}");
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"登录失败: {ex.Message}");
            return false;
        }
    }

    public List<User> GetAllUsers()
    {
        // 返回副本以防止外部修改
        return new List<User>(_users);
    }

    public User FindUserByUsername(string username)
    {
        // 使用foreach循环查找
        foreach (var user in _users)
        {
            if (user.Username == username)
                return user;
        }
        return null;
    }

    public bool DeleteUser(string username)
    {
        try
        {
            // 使用for循环进行删除（避免foreach的修改异常）
            for (int i = 0; i < _users.Count; i++)
            {
                if (_users[i].Username == username)
                {
                    _users.RemoveAt(i);
                    Console.WriteLine($"用户 {username} 删除成功！");
                    
                    // 如果删除的是当前登录用户，则退出登录
                    if (_currentUser?.Username == username)
                    {
                        _currentUser = null;
                    }
                    return true;
                }
            }
            
            Console.WriteLine($"用户 {username} 不存在！");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"删除用户失败: {ex.Message}");
            return false;
        }
    }

    public bool UpdateUser(User user)
    {
        try
        {
            if (user == null)
                throw new ArgumentNullException(nameof(user), "用户信息不能为空");
            
            // 使用for循环查找并更新
            for (int i = 0; i < _users.Count; i++)
            {
                if (_users[i].Username == user.Username)
                {
                    _users[i] = user;
                    Console.WriteLine($"用户 {user.Username} 更新成功！");
                    return true;
                }
            }
            
            Console.WriteLine($"用户 {user.Username} 不存在！");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"更新用户失败: {ex.Message}");
            return false;
        }
    }

    public void DisplayUserStatistics()
    {
        Console.WriteLine("\n=== 用户统计信息 ===");
        Console.WriteLine($"总用户数: {_users.Count}");
        
        if (_users.Count > 0)
        {
            // 使用foreach循环计算统计信息
            DateTime earliestDate = DateTime.MaxValue;
            DateTime latestDate = DateTime.MinValue;
            
            foreach (var user in _users)
            {
                if (user.RegistrationDate < earliestDate)
                    earliestDate = user.RegistrationDate;
                if (user.RegistrationDate > latestDate)
                    latestDate = user.RegistrationDate;
            }
            
            Console.WriteLine($"最早注册: {earliestDate:yyyy-MM-dd}");
            Console.WriteLine($"最近注册: {latestDate:yyyy-MM-dd}");
            Console.WriteLine($"系统运行: {(latestDate - earliestDate).Days} 天");
        }
    }

    // 流程控制方法
    public void ShowMainMenu()
    {
        while (true)
        {
            Console.WriteLine("\n=== 用户管理系统 ===");
            Console.WriteLine("1. 登录");
            Console.WriteLine("2. 注册");
            Console.WriteLine("3. 用户管理");
            Console.WriteLine("4. 显示所有用户");
            Console.WriteLine("5. 统计信息");
            Console.WriteLine("0. 退出");
            
            if (_currentUser != null)
            {
                Console.WriteLine($"当前用户: {_currentUser.Username}");
            }
            
            Console.Write("请选择: ");
            string choice = Console.ReadLine();
            
            switch (choice)
            {
                case "1":
                    ShowLoginMenu();
                    break;
                case "2":
                    ShowRegistrationMenu();
                    break;
                case "3":
                    if (_currentUser != null)
                    {
                        ShowUserManagementMenu();
                    }
                    else
                    {
                        Console.WriteLine("请先登录！");
                    }
                    break;
                case "4":
                    DisplayAllUsers();
                    break;
                case "5":
                    DisplayUserStatistics();
                    break;
                case "0":
                    Console.WriteLine("谢谢使用，再见！");
                    return;
                default:
                    Console.WriteLine("请输入有效数字(0-5)！");
                    break;
            }
        }
    }

    public void ShowRegistrationMenu()
    {
        Console.WriteLine("\n=== 用户注册 ===");
        
        try
        {
            Console.Write("请输入用户名: ");
            string username = Console.ReadLine()?.Trim();
            
            Console.Write("请输入密码: ");
            string password = Console.ReadLine();
            
            Console.Write("请确认密码: ");
            string confirmPassword = Console.ReadLine();
            
            Console.Write("请输入邮箱: ");
            string email = Console.ReadLine()?.Trim();
            
            User newUser = new User(username, password, email);
            Register(newUser, confirmPassword);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"注册过程中发生错误: {ex.Message}");
        }
    }

    public void ShowLoginMenu()
    {
        Console.WriteLine("\n=== 用户登录 ===");
        
        Console.Write("请输入用户名: ");
        string username = Console.ReadLine()?.Trim();
        
        Console.Write("请输入密码: ");
        string password = Console.ReadLine();
        
        Login(username, password);
    }

    public void ShowUserManagementMenu()
    {
        while (true)
        {
            Console.WriteLine("\n=== 用户管理 ===");
            Console.WriteLine("1. 查看个人信息");
            Console.WriteLine("2. 更新个人信息");
            Console.WriteLine("3. 删除用户");
            Console.WriteLine("4. 退出登录");
            Console.WriteLine("0. 返回主菜单");
            Console.Write("请选择: ");
            
            string choice = Console.ReadLine();
            
            switch (choice)
            {
                case "1":
                    DisplayCurrentUserInfo();
                    break;
                case "2":
                    UpdateCurrentUserInfo();
                    break;
                case "3":
                    DeleteCurrentUser();
                    return; // 删除后返回主菜单
                case "4":
                    Logout();
                    return; // 退出登录后返回主菜单
                case "0":
                    return;
                default:
                    Console.WriteLine("请输入有效数字(0-4)！");
                    break;
            }
        }
    }

    // 辅助方法
    private void DisplayAllUsers()
    {
        var allUsers = GetAllUsers();
        if (allUsers.Count == 0)
        {
            Console.WriteLine("没有用户信息！");
            return;
        }
        
        Console.WriteLine("\n=== 所有用户信息 ===");
        // 使用foreach循环显示所有用户
        int index = 1;
        foreach (var user in allUsers)
        {
            Console.WriteLine($"{index}. {user}");
            index++;
        }
    }

    private void DisplayCurrentUserInfo()
    {
        if (_currentUser != null)
        {
            Console.WriteLine("\n=== 个人信息 ===");
            Console.WriteLine(_currentUser);
        }
    }

    private void UpdateCurrentUserInfo()
    {
        if (_currentUser == null)
        {
            Console.WriteLine("请先登录！");
            return;
        }
        
        try
        {
            Console.WriteLine("\n=== 更新个人信息 ===");
            Console.Write("请输入新密码 (直接回车保持原密码): ");
            string newPassword = Console.ReadLine();
            
            Console.Write("请输入新邮箱: ");
            string newEmail = Console.ReadLine()?.Trim();
            
            User updatedUser = new User(
                _currentUser.Username,
                string.IsNullOrEmpty(newPassword) ? _currentUser.Password : newPassword,
                string.IsNullOrEmpty(newEmail) ? _currentUser.Email : newEmail
            );
            
            UpdateUser(updatedUser);
            _currentUser = updatedUser; // 更新当前用户引用
        }
        catch (Exception ex)
        {
            Console.WriteLine($"更新失败: {ex.Message}");
        }
    }

    private void DeleteCurrentUser()
    {
        if (_currentUser != null)
        {
            Console.Write($"确定要删除用户 {_currentUser.Username} 吗？(y/n): ");
            string confirm = Console.ReadLine()?.ToLower();
            
            if (confirm == "y" || confirm == "yes")
            {
                DeleteUser(_currentUser.Username);
            }
        }
    }

    private void Logout()
    {
        if (_currentUser != null)
        {
            Console.WriteLine($"用户 {_currentUser.Username} 已退出登录");
            _currentUser = null;
        }
    }
}
